{% extends 'layout/manage.html' %}
{% load static %}
{% load issues %}

{% block css %}
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-datepicker/css/bootstrap-datepicker.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-select/dist/css/bootstrap-select.min.css' %}">

    <style>
        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info pre {
            margin-top: -5px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #dddddd;
            color: #000;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }


        .editormd-fullscreen {
            z-index: 1001;
        }

        #content {
            width: 100%;
            background-color: rgba(241, 241, 241, .98);
            height: 150px;
            padding: 15px;
            resize: none;
            border: 1px solid rgb(193, 222, 250);
            border-radius: 4px;
            outline-color: rgba(83, 160, 231, 0.61);
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container-fluid" style="padding: 20px 0;">
        <div class="col-sm-7">
            <div class="panel panel-default">
                <div class="panel-heading edit-heading">
                    <div>
                        <i class="fa fa-edit" aria-hidden="true"></i> 更新问题
                    </div>
                </div>
                <div class="panel-body">
                    <form id="addForm" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">问题类型</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.issues_type }}
                                </div>
                                <div class="error-msg"></div>
                            </div>
                            <div class="error-msg"></div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}" class="col-sm-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.subject }}
                                </div>
                                <div class="error-msg"></div>
                            </div>

                        </div>
                        <div class="form-group">
                            <label for="{{ form.module.id_for_label }}" class="col-sm-2 control-label">{{ form.module.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.module }}
                                </div>
                                <div class="error-msg"></div>
                            </div>

                        </div>
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}" class="col-sm-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-sm-10">
                                <div id="editor">
                                    {{ form.desc }}
                                </div>
                                <div class="error-msg"></div>
                            </div>

                        </div>

                        <div class="form-group clearfix">
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.status.id_for_label }}" class="col-sm-3 control-label">{{ form.status.label }}</label>
                                    <div class="col-sm-9">
                                        <div>
                                            {{ form.status }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.priority.id_for_label }}" class="col-sm-3 control-label">{{ form.priority.label }}</label>
                                    <div class="col-sm-9">
                                        <div>
                                            {{ form.priority }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.assign.id_for_label }}" class="col-sm-3 control-label">{{ form.assign.label }}</label>
                                    <div class="col-sm-9">
                                        {{ form.assign }}
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.attention.id_for_label }}" class="col-sm-3 control-label">{{ form.attention.label }}</label>
                                    <div class="col-sm-9">
                                        {{ form.attention }}
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.start_date.id_for_label }}" class="col-sm-3 control-label">{{ form.start_date.label }}</label>
                                    <div class="col-sm-9">
                                        <div class="input-group">
                                            <span class="input-group-addon"><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                            {{ form.start_date }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.end_date.id_for_label }}" class="col-sm-3 control-label">{{ form.end_date.label }}</label>
                                    <div class="col-sm-9">
                                        <div class="input-group">
                                            <span class="input-group-addon"><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                            {{ form.end_date }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.mode.id_for_label }}" class="col-sm-3 control-label">{{ form.mode.label }}</label>
                                    <div class="col-sm-9">
                                        <div>
                                            {{ form.mode }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                            <div class="col-sm-1"></div>
                            <div class="col-sm-5 pd-0">
                                <div class="form-group">
                                    <label for="{{ form.parent.id_for_label }}" class="col-sm-3 control-label">{{ form.parent.label }}</label>
                                    <div class="col-sm-9">
                                        <div>
                                            {{ form.parent }}
                                        </div>
                                        <div class="error-msg"></div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-sm-5">
            <div class="panel panel-default">
                <!-- Default panel contents -->
                <div class="panel-heading">操作记录</div>
                <div class="panel-body comment-area">
                    <div class="comment-list">
                    </div>
                    <hr>
                    <div class="comment-text" id="commentText">
                        <div class="form-group">
                            <textarea id="content" rows="6" cols="form-control" placeholder="请输入要回复的内容"></textarea>
                            <span class="error-msg"></span>
                        </div>

                        <input class="btn btn-primary" type="button" id="btnSubmit" value="提交">
                        <div class="reply-user hide" id="replyUser">
                            回复<span></span>
                            <i class="fa fa-times-circle" aria-hidden="true"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

    {#    问题讨论列表模板#}
    <div class="hide" id="recordTemplate">
        <div class="item clearfix">
            <div class="left-avatar"></div>
            <div class="right-info">
                {#                内容#}
                <pre></pre>
                <div class="desc">
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="type"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="user"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="date"></span>
                    </div>

                    <a href="#commentText" class="reply">
                        <i class="fa fa-comment-o" aria-hidden="true"></i> 回复
                    </a>
                </div>
            </div>
            <div class="child"></div>
        </div>
    </div>
{% endblock %}

{% block js %}
    <script src="{% static 'plugins/editor-md/editormd.amd.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/dist/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/dist/js/i18n/defaults-zh_CN.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/js/bootstrap-datepicker.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>


    <script>
        var WIKI_UPLOAD_URL = "{% url 'wiki_upload' project_id=request.bug_platform.project.id %}"
        var ISSUES_RECORD_URL = "{% url 'issues_record' project_id=request.bug_platform.project.id issues_id=issues_object.id %}"
        var EDITOR;   // 用作后面获取mk里面的内容
        var ISSUES_CHANGE_URL = "{% url 'issues_change' project_id=request.bug_platform.project.id issues_id=issues_object.id %}"

        $(function () {
            initEditorMd();
            initDatePicker();   // 出错了
            inisIssuesRecord();

            btnChangIssues();
            binRepl();
            bindCancelReplyUser();

            btnSubmit();  // 提交评论或者回复
        });

        /*
        初始化bootstrap-datepicker 插件
        * */
        function initDatePicker() {
            // JQuery.noConflict();//让jquery放弃对$的使用权，交给其他js框架使用
            {#console.log(5)#}
            $('#id_start_date, #id_end_date').datepicker({
                format: 'yyyy-mm-dd',   // 选后的展示格式
                startDate: '0',      //  从什么时候开始选择，0表示从中间开始选，以前的不能选
                language: 'zh-CN',  //  中文显示
                autoclose: true     // 点击其他地方 选择框关闭
            });
        }

        /*
        初始化markdown编辑器(textare转化为编辑器)
        * */
        function initEditorMd() {
            EDITOR = editormd('editor', {
                placeholder: '请输入内容',
                width: "98%",
                height: 300,
                path: "{% static 'plugins/editor-md/lib/' %}",
                imageUpload: true,  // 支持本地上传
                imageFormats: ['jpg', 'png', 'jpeg', 'gif'],
                imageUploadURL: WIKI_UPLOAD_URL,
                // 不固定在页面
                toolbarAutoFixed: false,
                // 自定义mk上的按钮
                toolbarIcons: function () {
                    return ["undo", "redo", "|", "bold", "hr", "|", "preview", "watch", '|', 'image', "||", 'save']
                },
                // 自定义mk上的按钮
                toolbarCustomIcons: {
                    save: '<input type="button" value="保存" class="btn btn-success btn-sm" onclick="saveDest();" />'
                },
                // 加载时 设置默认为预览 而不是编辑显示
                onload: function () {
                    this.previewing();
                }
            });
        }

        /*
        问题评论的初始化
         */
        function inisIssuesRecord() {
            $.ajax({
                url: ISSUES_RECORD_URL,
                type: 'GET',
                dataType: 'JSON',
                success: function (res) {
                    console.log(res)
                    if (res.status) {
                        // res.data  [{}, {}, {}]
                        console.log(res.data)
                        // 循环拿到的每一个数据
                        $.each(res.data, function (index, item) {
                            createRecordNode(item)
                        });
                    } else {
                        alert('不ok')
                    }
                }
            })
        }

        /*
        创建操作记录节点
         */
        function createRecordNode(nodeDict) {
            var $item = $('#recordTemplate').find('.item').clone();     // 拷贝所有节点
            {#console.log(nodeDict.parent_id)#}
            $item.find('.left-avatar').html(nodeDict.creator[0].toUpperCase());  // 拿到当前的第一个变成大写当头像
            {#$item.find('pre').html(nodeDict.content);      // 内容#}
            $item.find('.right-info').find('pre').html(nodeDict.content);      // 内容
            $item.find('.user').html(nodeDict.creator);   //  用户名
            $item.find('.type').html(nodeDict.reply_type_text);     // 回复的谁
            $item.find('.date').html(nodeDict.datetime);        // 创建时间
            $item.attr({id: nodeDict.id, username: nodeDict.creator})       // 给每个整体加上两个标签
            {#console.log($item)#}

            if (nodeDict.parent_id) {   // 判断是否有父节点
                // 挂在谁的下面
                $('#' + nodeDict.parent_id).children('.child').append($item);
            } else {
                // 根下
                $('.comment-list').append($item);
            }
        }


        function btnChangIssues() {
            // 找到所有的input【输入框绑定change 事件
            $('#addForm').find('.form-control').change(function () {
                // 内容变更
                var postDict = {'name': $(this).attr('name'), 'value': $(this).val()}
                console.log(postDict);
                postAjaxData(postDict);
            })
        }

        // 自定义mk的按钮函数
        function saveDest() {
            var postDict = {'name': 'desc', 'value': EDITOR.getValue()}
            console.log(postDict);
            postAjaxData(postDict);
        }

        // 向后台发送修改好的数据
        function postAjaxData(postDict) {
            // 重置错误信息
            $('#id_' + postDict.name).parent().next('.error-msg').text('')

            $.ajax({
                url: ISSUES_CHANGE_URL,
                type: 'POST',
                header: {'Content-Type': 'application/json:charset=utf-8'}, // 请求头 告诉后台这是json数据
                data: JSON.stringify(postDict),      // 成字符串 后端需要json.loads(request.body.decode('utf-8')) 反序列化
                // data: postDict,
                dataType: 'JSON',
                success: function (res) {
                    {#console.log(res)#}
                    if (res.status) {
                        createRecordNode(res.data)  // 没有成功
                    } else {
                        $('#id_' + postDict.name).parent().next('.error-msg').text(res.error)
                    }
                }
            })
        }


        /*
        回复问题
         */
        function binRepl() {
            // on 事件委托
            $('.comment-list').on('click', '.reply', function () {
                console.log(123)
                var $item = $(this).parent().parent().parent();
                var id = $item.attr('id');
                var username = $item.attr('username');

                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        /*
        取消回复
         */
        function bindCancelReplyUser() {
            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text('');
            })
        }


        /*
        点击提交发送ajax请求【回复 & 评论
         */
        function btnSubmit() {
            $('#btnSubmit').click(function () {
                // 点击按钮之前清空错误信息
                $('#commentText .error-msg').text('')

                $.ajax({
                    url: ISSUES_RECORD_URL,
                    type: "POST",
                    data: {content: $('#content').val(), reply: $('#replyUser').attr('parent-id')},
                    dataType: 'JSON',
                    success: function (res) {
                        console.log(res)
                        if (res.status) {
                            // 成功之后 展示在相应位置并清空输入框和清除回复谁
                            createRecordNode(res.data);
                            $('#content').val();
                            $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text('');
                        } else {
                            $.each(res.error, function (k, v) {
                                $('#content').next('error-msg').text(v[0])
                            })
                        }
                    }
                })
            })
        }
    </script>



{% endblock %}